package top.bug.blog.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.bug.blog.common.BasePO;
import top.bug.blog.constant.CommonConstants;
import top.bug.blog.entity.dto.common.BatchRequest;
import top.bug.blog.entity.dto.tag.TagAddRequest;
import top.bug.blog.entity.dto.tag.TagQueryRequest;
import top.bug.blog.entity.dto.tag.TagUpdateRequest;
import top.bug.blog.entity.po.Tag;
import top.bug.blog.enums.ErrorCode;
import top.bug.blog.exception.BussinessException;
import top.bug.blog.mapper.ArticleTagMapper;
import top.bug.blog.mapper.TagMapper;
import top.bug.blog.service.TagService;
import top.bug.blog.utils.QueryWrapperUtils;
import top.bug.blog.utils.StrUtils;

import javax.annotation.Resource;
import java.util.List;

import static top.bug.blog.utils.StrUtils.isNotBlank;

/**
 * @author <a href="https://github.com/jiusi66">九思.</a>
 * @email 10837907@qq.com
 * @from <a href="https://www.52bug.top">递归茶馆-www.52bug.top</a>
 * @description 标签 实现类
 */
@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag> implements TagService {
    @Resource
    private TagMapper tagMapper;
    @Resource
    private ArticleTagMapper articleTagMapper;

    // region 后台接口

    @Override
    public Page<Tag> getList(TagQueryRequest queryRequest) {
        if (null == queryRequest) {
            throw new BussinessException(ErrorCode.PARAM_NOT_COMPLETE);
        }
        Page<Tag> page = new Page<>(queryRequest.getPageNum(), queryRequest.getPageSize());
        String name = queryRequest.getName();
        String status = queryRequest.getStatus();
        LambdaQueryWrapper<Tag> queryWrapper = new LambdaQueryWrapper<Tag>()
                .like(isNotBlank(name), Tag::getName, name)
                .eq(isNotBlank(status), Tag::getStatus, status);
        // 时间范围参数
        QueryWrapperUtils.addTimeRangeCondition(queryWrapper, queryRequest.getCreateTimeRange(), Tag::getCreateOn);
        QueryWrapperUtils.addTimeRangeCondition(queryWrapper, queryRequest.getUpdateTimeRange(), Tag::getUpdateOn);
        tagMapper.selectPage(page, queryWrapper);
        return page;
    }

    @Override
    public List<Tag> getByIds(BatchRequest batchRequest) {
        if (null == batchRequest) {
            throw new BussinessException(ErrorCode.PARAM_NOT_COMPLETE);
        }
        List<String> ids = batchRequest.getIds();
        if (CollectionUtil.isEmpty(ids)) {
            return null;
        }
        return tagMapper.selectBatchIds(ids);
    }

    @Override
    public Boolean add(TagAddRequest addRequest) {
        // 必填项校验
        String name = addRequest.getName();
        if (StrUtils.isAnyBlank(name)) {
            throw new BussinessException(ErrorCode.PARAM_NOT_COMPLETE);
        }
        Tag tag = new Tag();
        BeanUtil.copyProperties(addRequest, tag);
        // 默认值填充
        tag.setStatus(CommonConstants.STATUS_ENABLE);
        // 保存用户（唯一性由数据库层面进行控制）
        boolean save = false;
        try {
            save = this.save(tag);
        } catch (DuplicateKeyException e) {
            throw new BussinessException(ErrorCode.DATA_ALREADY_EXISTED);
        }
        return save;
    }

    @Override
    public Boolean edit(TagUpdateRequest updateRequest) {
        if (null == updateRequest || StrUtil.isEmpty(updateRequest.getId())) {
            throw new BussinessException(ErrorCode.PARAM_NOT_COMPLETE);
        }
        Tag tag = new Tag();
        BeanUtil.copyProperties(updateRequest, tag);
        return this.updateById(tag);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(BatchRequest batchRequest) {
        if (null == batchRequest || CollUtil.isEmpty(batchRequest.getIds())) {
            throw new BussinessException(ErrorCode.PARAM_NOT_COMPLETE);
        }
        return this.removeBatchByIds(batchRequest.getIds());
    }

    // endregion

    // region 前台接口

    @Override
    public List<Tag> getHotList() {
        // 获取热门标签集合，默认10个
        int hotNum = 10;
        List<String> ids = articleTagMapper.getHotTagIds(hotNum);
        // 根据id查询标签信息
        return tagMapper.selectList(new LambdaQueryWrapper<Tag>()
                .eq(Tag::getStatus, CommonConstants.STATUS_ENABLE)
                .in(BasePO::getId, ids));
    }

    // endregion

}